#include <iostream>
using namespace std;
void matrixMultiplyCPU(const int *a, const int *b, int *c, int width);
void twoMultiplyPrint(const int *c);
void MultiplyPrint(const int *c,int width);
int main() {
//    int a[4] = {1, 2, 3, 4};
//    int b[4] = {5, 6, 7, 8};
//    int c[4] = {0};
//    matrixMultiplyCPU(a, b, c, 2);
//    MultiplyPrint(c,2);

//    int a[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
//    int b[9] = {2, 4, 6, 1, 3, 5, 7, 9, 11};
//    int c[9] = {0};
//    matrixMultiplyCPU(a, b, c, 3);
//    MultiplyPrint(c,3);

    int a[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
    int b[16] = {4, 3, 2, 1, 8, 7, 6, 5, 12, 11, 10, 9, 16, 15, 14, 13};
    int c[16] = {0};
    matrixMultiplyCPU(a, b, c, 4);
    MultiplyPrint(c,4);
    return 0;
}
__global__ void matrixMultiplyCPU(float* A, float* B, float* C, int width) {
    __shared__ float As[TILE_WIDTH][TILE_WIDTH];
    __shared__ float Bs[TILE_WIDTH][TILE_WIDTH];

    int bx = blockIdx.x;  int by = blockIdx.y;
    int tx = threadIdx.x; int ty = threadIdx.y;

    int Row = by * TILE_WIDTH + ty;
    int Col = bx * TILE_WIDTH + tx;

    float Pvalue = 0;

    for (int m = 0; m < width/TILE_WIDTH; ++m) {
        As[ty][tx] = A[Row*width + (m*TILE_WIDTH + tx)];
        Bs[ty][tx] = B[(m*TILE_WIDTH + ty)*width + Col];

        __syncthreads();

        for (int k = 0; k < TILE_WIDTH; ++k)
            Pvalue += As[ty][k] * Bs[k][tx];

        __syncthreads();
    }

    C[Row*width+Col] = Pvalue;
}

void MultiplyPrint(const int *c,int width) {
    cout << "c = {";
    for (int i = 0; i < width; ++i) {
        cout << c[i] << ", ";
    }
    cout << "}" << endl;
}